package com.jxm.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: jxm
 * @Description: 写数据
 * @Date: 2024-2-7 14:33
 * @Version: 1.0
 */
public class FileChannelDemo2 {

    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new
                RandomAccessFile("f:\\file\\01.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf1 = ByteBuffer.allocate(48);

        String newData = "New String to write to file..." +
                System.currentTimeMillis();

        buf1.clear();
        buf1.put(newData.getBytes());
        buf1.flip();//反转读写模式
        while(buf1.hasRemaining()) {
            inChannel.write(buf1);
        }
        inChannel.close();
    }
}
